<template>
  <div class="personal-memory-container">
    <el-tabs v-model="activeTab" @tab-change="handleTabChange">
      <!-- 个人记忆标签页 -->
      <el-tab-pane label="个人记忆向量库" name="memory">
        <el-card shadow="hover">
          <template #header>
            <div style="display: flex; justify-content: space-between; align-items: center;">
              <span>个人记忆向量库管理</span>
              <el-space :size="8" wrap>
                <el-button type="danger" @click="handleBatchDelete" :disabled="selectedRows.length === 0" :loading="isDeleting">
                  <el-icon><Delete /></el-icon>
                  批量删除
                </el-button>
                <el-button type="danger" plain @click="handleClearAllMemory" :loading="isClearingAll">
                  <el-icon><Delete /></el-icon>
                  一键清空
                </el-button>
                <el-button type="primary" @click="handleQuery">
                  <el-icon><Refresh /></el-icon>
                  刷新
                </el-button>
              </el-space>
            </div>
          </template>
      
      <el-form :inline="true">
        <el-form-item label="用户ID">
          <el-input-number v-model="state.filters.userId" :min="0" placeholder="全部" style="width:160px" clearable />
        </el-form-item>
        <el-form-item label="关键词">
          <el-input v-model="state.filters.keyword" placeholder="搜索记忆内容..." style="width:260px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetFilters">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="full-table" shadow="hover" style="margin-top: 5px">
      <el-table :data="state.tableData" v-loading="state.loading" row-key="id" border @selection-change="onSelectionChange">
        <el-table-column type="selection" width="50" />
        <el-table-column prop="id" label="ID" width="120" />
        <el-table-column prop="userId" label="用户ID" width="100" />
        <el-table-column prop="role" label="角色" width="100">
          <template #default="{ row }">
            <el-tag :type="row.role === 'user' ? 'primary' : 'success'" size="small">
              {{ row.role === 'user' ? '用户' : '小智' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="记忆内容" min-width="300" show-overflow-tooltip />
        <el-table-column prop="conversationId" label="对话ID" width="200" show-overflow-tooltip />
        <el-table-column prop="createdAt" label="创建时间" width="180" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button size="small" type="danger" @click="deleteMemory(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
          <el-pagination
            v-model:current-page="state.params.page"
            v-model:page-size="state.params.pageSize"
            :total="state.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleQuery"
            @current-change="handleQuery"
            style="margin-top: 20px; text-align: right;"
          />
        </el-card>
      </el-tab-pane>

      <!-- 对话历史标签页 -->
      <el-tab-pane label="对话历史（MySQL）" name="history">
        <el-card shadow="hover">
          <template #header>
            <div style="display: flex; justify-content: space-between; align-items: center;">
              <span>对话历史管理（MySQL数据库）</span>
              <el-space :size="8" wrap>
                <el-button type="danger" @click="handleBatchDeleteHistory" :disabled="selectedHistoryRows.length === 0" :loading="isDeletingHistory">
                  <el-icon><Delete /></el-icon>
                  批量删除
                </el-button>
                <el-button type="danger" plain @click="handleClearAllHistory" :loading="isClearingAllHistory">
                  <el-icon><Delete /></el-icon>
                  一键清空
                </el-button>
                <el-button type="primary" @click="handleQueryHistory">
                  <el-icon><Refresh /></el-icon>
                  刷新
                </el-button>
              </el-space>
            </div>
          </template>
          
          <el-form :inline="true">
            <el-form-item label="用户ID">
              <el-input-number v-model="historyState.filters.userId" :min="0" placeholder="全部" style="width:160px" clearable />
            </el-form-item>
            <el-form-item label="对话ID">
              <el-input v-model="historyState.filters.conversationId" placeholder="对话ID..." style="width:260px" clearable />
            </el-form-item>
            <el-form-item label="关键词">
              <el-input v-model="historyState.filters.keyword" placeholder="搜索消息内容..." style="width:260px" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQueryHistory">查询</el-button>
              <el-button @click="resetHistoryFilters">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <el-card class="full-table" shadow="hover" style="margin-top: 5px">
          <el-table :data="historyState.tableData" v-loading="historyState.loading" row-key="id" border @selection-change="onHistorySelectionChange">
            <el-table-column type="selection" width="50" />
            <el-table-column prop="id" label="ID" width="100" />
            <el-table-column prop="userId" label="用户ID" width="100" />
            <el-table-column prop="userName" label="用户名" width="120" />
            <el-table-column prop="isFromUser" label="发送者" width="100">
              <template #default="{ row }">
                <el-tag :type="row.isFromUser ? 'primary' : 'success'" size="small">
                  {{ row.isFromUser ? '用户' : '小智' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="message" label="消息内容" min-width="300" show-overflow-tooltip />
            <el-table-column prop="conversationId" label="对话ID" width="200" show-overflow-tooltip />
            <el-table-column prop="timestamp" label="时间" width="180" />
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="{ row }">
                <el-button size="small" type="danger" @click="deleteHistory(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <el-pagination
            v-model:current-page="historyState.params.page"
            v-model:page-size="historyState.params.pageSize"
            :total="historyState.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleQueryHistory"
            @current-change="handleQueryHistory"
            style="margin-top: 20px; text-align: right;"
          />
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script lang="ts" setup name="PersonalMemory">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Refresh, Delete } from '@element-plus/icons-vue';
import { useCustomerServiceApi, type PersonalMemoryOutput, type PersonalMemoryPageInput, type ConversationHistoryOutput, type ConversationHistoryPageInput } from '/@/api/customerService';

const customerServiceApi = useCustomerServiceApi();

const activeTab = ref('memory');

const state = reactive({
  loading: false,
  tableData: [] as PersonalMemoryOutput[],
  total: 0,
  params: { page: 1, pageSize: 20 },
  filters: { userId: undefined as number | undefined, keyword: '' }
});

const selectedRows = ref<PersonalMemoryOutput[]>([]);
const isDeleting = ref(false);
const isClearingAll = ref(false);

const historyState = reactive({
  loading: false,
  tableData: [] as ConversationHistoryOutput[],
  total: 0,
  params: { page: 1, pageSize: 20 },
  filters: { userId: undefined as number | undefined, conversationId: '', keyword: '' }
});

const selectedHistoryRows = ref<ConversationHistoryOutput[]>([]);
const isDeletingHistory = ref(false);
const isClearingAllHistory = ref(false);

// 查询个人记忆
const handleQuery = async () => {
  state.loading = true;
  try {
    const params: PersonalMemoryPageInput = {
      ...state.params,
      userId: state.filters.userId,
      keyword: state.filters.keyword || undefined
    };
    const res = await customerServiceApi.getPersonalMemoryPage(params);
    console.log('API完整响应:', res);
    console.log('响应数据:', res.data);
    
    // Furion框架返回格式：
    // { code: 200, type: 'success', result: { ... } } 或
    // { code: 200, type: 'success', data: { ... } }
    const responseData = res.data;
    
    if (responseData?.code === 200 || responseData?.type === 'success') {
      // 尝试多种可能的字段名
      const result = responseData?.result || responseData?.data || responseData;
      
      if (result && typeof result === 'object') {
        // 检查是否是PersonalMemoryPageResult格式
        if (Array.isArray(result.items) || Array.isArray(result.Items)) {
          state.tableData = result.items || result.Items || [];
          state.total = result.total || result.Total || 0;
        } else if (Array.isArray(result)) {
          // 如果直接返回数组
          state.tableData = result;
          state.total = result.length;
        } else {
          // 如果是其他格式，尝试提取数据
          console.warn('意外的响应格式:', result);
          state.tableData = [];
          state.total = 0;
        }
      } else {
        state.tableData = [];
        state.total = 0;
      }
      
      if (state.total === 0 && state.tableData.length === 0) {
        console.log('查询成功，但数据为空');
      }
    } else {
      const errorMsg = responseData?.message || responseData?.msg || '查询失败';
      console.error('查询失败:', errorMsg, responseData);
      ElMessage.error(errorMsg);
    }
  } catch (e: any) {
    console.error(e);
    ElMessage.error(e.message || '查询失败');
  } finally {
    state.loading = false;
  }
};

// 重置筛选条件
const resetFilters = () => {
  state.filters = { userId: undefined, keyword: '' };
  handleQuery();
};

// 删除记忆
const deleteMemory = async (row: PersonalMemoryOutput) => {
  try {
    await ElMessageBox.confirm(`确定要删除这条记忆吗？\n${row.content.substring(0, 50)}...`, '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });

    isDeleting.value = true;
    try {
      await customerServiceApi.deletePersonalMemory({ id: row.id });
      ElMessage.success('删除成功');
      handleQuery();
    } catch (e: any) {
      console.error(e);
      ElMessage.error(e.message || '删除失败');
    } finally {
      isDeleting.value = false;
    }
  } catch {
    // 用户取消
  }
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的记忆');
    return;
  }

  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 条记忆吗？`, '批量删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });

    isDeleting.value = true;
    try {
      const ids = selectedRows.value.map(row => row.id);
      await customerServiceApi.batchDeletePersonalMemory(ids);
      ElMessage.success(`成功删除 ${ids.length} 条记忆`);
      selectedRows.value = [];
      handleQuery();
    } catch (e: any) {
      console.error(e);
      ElMessage.error(e.message || '批量删除失败');
    } finally {
      isDeleting.value = false;
    }
  } catch {
    // 用户取消
  }
};

// 选择变化
const onSelectionChange = (rows: PersonalMemoryOutput[]) => {
  selectedRows.value = rows;
};

// 标签页切换
const handleTabChange = (tabName: string) => {
  if (tabName === 'memory') {
    handleQuery();
  } else if (tabName === 'history') {
    handleQueryHistory();
  }
};

// 查询对话历史
const handleQueryHistory = async () => {
  historyState.loading = true;
  try {
    const params: ConversationHistoryPageInput = {
      ...historyState.params,
      userId: historyState.filters.userId,
      conversationId: historyState.filters.conversationId || undefined,
      keyword: historyState.filters.keyword || undefined
    };
    const res = await customerServiceApi.getConversationHistoryPage(params);
    const responseData = res.data;
    
    if (responseData?.code === 200 || responseData?.type === 'success') {
      const result = responseData?.result || responseData?.data || responseData;
      
      if (result && typeof result === 'object') {
        if (Array.isArray(result.items) || Array.isArray(result.Items)) {
          historyState.tableData = result.items || result.Items || [];
          historyState.total = result.total || result.Total || 0;
        } else if (Array.isArray(result)) {
          historyState.tableData = result;
          historyState.total = result.length;
        } else {
          historyState.tableData = [];
          historyState.total = 0;
        }
      } else {
        historyState.tableData = [];
        historyState.total = 0;
      }
    } else {
      const errorMsg = responseData?.message || responseData?.msg || '查询失败';
      ElMessage.error(errorMsg);
    }
  } catch (e: any) {
    console.error(e);
    ElMessage.error(e.message || '查询失败');
  } finally {
    historyState.loading = false;
  }
};

// 重置对话历史筛选条件
const resetHistoryFilters = () => {
  historyState.filters = { userId: undefined, conversationId: '', keyword: '' };
  handleQueryHistory();
};

// 删除对话历史
const deleteHistory = async (row: ConversationHistoryOutput) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除这条对话历史吗？\n发送者：${row.isFromUser ? '用户' : '小智'}\n内容：${row.message.substring(0, 50)}${row.message.length > 50 ? '...' : ''}`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    isDeletingHistory.value = true;
    try {
      await customerServiceApi.deleteConversationHistory({ id: row.id });
      ElMessage.success('删除成功');
      handleQueryHistory();
    } catch (e: any) {
      console.error(e);
      ElMessage.error(e.message || '删除失败');
    } finally {
      isDeletingHistory.value = false;
    }
  } catch {
    // 用户取消
  }
};

// 批量删除对话历史
const handleBatchDeleteHistory = async () => {
  if (selectedHistoryRows.value.length === 0) {
    ElMessage.warning('请选择要删除的对话历史');
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedHistoryRows.value.length} 条对话历史吗？\n\n⚠️ 警告：这是真删除，删除后无法恢复！`,
      '批量删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    isDeletingHistory.value = true;
    try {
      const ids = selectedHistoryRows.value.map(row => row.id);
      await customerServiceApi.batchDeleteConversationHistory(ids);
      ElMessage.success(`成功删除 ${ids.length} 条对话历史`);
      selectedHistoryRows.value = [];
      handleQueryHistory();
    } catch (e: any) {
      console.error(e);
      ElMessage.error(e.message || '批量删除失败');
    } finally {
      isDeletingHistory.value = false;
    }
  } catch {
    // 用户取消
  }
};

// 对话历史选择变化
const onHistorySelectionChange = (rows: ConversationHistoryOutput[]) => {
  selectedHistoryRows.value = rows;
};

// 一键清空所有个人记忆
const handleClearAllMemory = async () => {
  try {
    await ElMessageBox.confirm(
      '⚠️ 警告：此操作将清空所有个人记忆（Qdrant向量数据库）！\n\n' +
      '• 此操作不可恢复\n' +
      '• 所有向量记忆将被永久删除\n' +
      '• 包括所有用户的个人记忆\n\n' +
      '确定要继续吗？',
      '一键清空确认',
      {
        confirmButtonText: '确定清空',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: false,
      }
    );

    isClearingAll.value = true;
    try {
      await customerServiceApi.clearAllPersonalMemory();
      ElMessage.success('清空所有个人记忆成功');
      selectedRows.value = [];
      handleQuery();
    } catch (e: any) {
      console.error(e);
      ElMessage.error(e.message || '清空失败');
    } finally {
      isClearingAll.value = false;
    }
  } catch {
    // 用户取消
  }
};

// 一键清空所有对话历史
const handleClearAllHistory = async () => {
  try {
    await ElMessageBox.confirm(
      '⚠️ 警告：此操作将清空所有对话历史（MySQL数据库）！\n\n' +
      '• 此操作不可恢复\n' +
      '• 所有对话记录将被永久删除\n' +
      '• 包括所有用户的对话历史\n\n' +
      '确定要继续吗？',
      '一键清空确认',
      {
        confirmButtonText: '确定清空',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: false,
      }
    );

    isClearingAllHistory.value = true;
    try {
      const res = await customerServiceApi.clearAllConversationHistory();
      const count = res.data?.result || res.data?.data || 0;
      ElMessage.success(`清空所有对话历史成功，共删除 ${count} 条记录`);
      selectedHistoryRows.value = [];
      handleQueryHistory();
    } catch (e: any) {
      console.error(e);
      ElMessage.error(e.message || '清空失败');
    } finally {
      isClearingAllHistory.value = false;
    }
  } catch {
    // 用户取消
  }
};

// 初始化
onMounted(() => {
  handleQuery();
});
</script>

<style scoped>
.personal-memory-container {
  padding: 20px;
}

.full-table {
  width: 100%;
}
</style>

